package com.synjones.network;

import android.util.Pair;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.synjones.entry.ServerResult;
import com.synjones.entry.SignPerson;
import com.synjones.util.MD5Utils;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.TimeUnit;

import okhttp3.HttpUrl;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class Api {


    private static final int timeout = 1500;
    private static Gson gson = new Gson();

    private static final MediaType mediaType = MediaType.parse("application/x-www-form-urlencoded; charset=utf-8");

//    private static String serverAddress = "http://192.168.43.158:8080";
    private static String serverAddress = "http://192.168.8.102:8080";
//    private static String serverAddress = "http://116.62.57.42:60005";

    /**
     * 获取签到的信息展示在识别页面
     * @param md5Number 证件号（md5加密的证件号）
     */
    private static String dataByCardNumberApi = serverAddress +"/sign/dataByCardNumber";

    /**
     * 代签时通过名字获取系统内的信息
     * @param name 代签人输入的名字
     */
    private static String dataByNameApi = serverAddress +"/sign/dataByName";

    /**
     * @param invitationCode 接待号（人员唯一码）
     * @param name 代领人姓名（如果是本人领取，此字段为空）
     * @param md5Number 证件号（md5加密的证件号）
     * @param oneself 是否本人领取（1：是，0：否）
     * @param documentNumber 代领人身份证号（如果是本人领取，此字段为空）
     * @return findNot未找到,signed已签到,success签到成功,pushFail推送失败
     */
    private static String signApi = serverAddress +"/sign/sign";

    /**
     *
     * @param md5Number
     * @param name
     * @return msg : md5 , no , name 通过何种方式查找到的
     */
    private static String signInfoApi = serverAddress + "/sign/signInfo";

    public static Pair<String, SignPerson> getSignInfoByIdNo(String idcardNo){
        String md5Number = MD5Utils.toMD5(idcardNo);
        HttpUrl url = HttpUrl.parse(dataByCardNumberApi).newBuilder()
                .addQueryParameter("md5Number", md5Number)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = getClient().newCall(request).execute()) {
            String data = response.body().string();
            ServerResult<SignPerson> presult = gson.fromJson(data, new TypeToken<ServerResult<SignPerson>>() {
            }.getType());
            if (presult.getCode() == 200){
                return new Pair<>("200", presult.getData());
            }else
                return new Pair<>("500", new SignPerson());
        } catch (IOException e) {
            e.printStackTrace();
            return new Pair<>("600", new SignPerson());
        }
    }

    public static Pair<String, List<SignPerson>> dataByName(String name){
        HttpUrl url = HttpUrl.parse(dataByNameApi).newBuilder()
                .addQueryParameter("name", name)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = getClient().newCall(request).execute()) {
            String data = response.body().string();
            ServerResult<List<SignPerson>> presult = gson.fromJson(data, new TypeToken<ServerResult<List<SignPerson>>>() {
            }.getType());
            if (presult.getCode() == 200){
                return new Pair<>("200", presult.getData());
            }else
                return new Pair<>("500", null);
        } catch (IOException e) {
            e.printStackTrace();
            return new Pair<>("600", null);
        }
    }

    public static String sign(String invitationCode,String name,String oneself,String idcardNo,
                              String documentNumber,String documentNumberReal){
        String md5Number = MD5Utils.toMD5(idcardNo);
        HttpUrl url = HttpUrl.parse(signApi).newBuilder()
                .addQueryParameter("invitationCode", invitationCode)
                .addQueryParameter("name", name)
                .addQueryParameter("oneself", oneself)
                .addQueryParameter("md5Number", md5Number)
                .addQueryParameter("documentNumber", documentNumber)
                .addQueryParameter("documentNumberReal", documentNumberReal)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .post(RequestBody.create(mediaType,""))
                .build();
        try (Response response = getClient().newCall(request).execute()) {
            String data = response.body().string();
            ServerResult<String> presult = gson.fromJson(data, new TypeToken<ServerResult<String>>() {
            }.getType());
            if (presult.getCode() == 200){
                return presult.getData();
            }else
                return "500";
        } catch (IOException e) {
            e.printStackTrace();
            return "600";
        }
    }

    public static Pair<String, List<SignPerson>> signInfo(String name,String idcardno){
        String md5Number = MD5Utils.toMD5(idcardno);
        HttpUrl url = HttpUrl.parse(signInfoApi).newBuilder()
                .addQueryParameter("name", name)
                .addQueryParameter("md5Number", md5Number)
                .build();
        Request request = new Request.Builder()
                .url(url)
                .build();
        try (Response response = getClient().newCall(request).execute()) {
            String data = response.body().string();
            ServerResult<List<SignPerson>> presult = gson.fromJson(data, new TypeToken<ServerResult<List<SignPerson>>>() {
            }.getType());
            if (presult.getCode() == 200){
                return new Pair<>(presult.getMessage(), presult.getData());
            }else
                return new Pair<>("500", null);
        } catch (IOException e) {
            e.printStackTrace();
            return new Pair<>("600", null);
        }
    }
    private static OkHttpClient getClient(){
        return new OkHttpClient.Builder()
                .connectTimeout(timeout, TimeUnit.MILLISECONDS)
                .writeTimeout(timeout, TimeUnit.MILLISECONDS)
                .readTimeout(timeout, TimeUnit.MILLISECONDS)
                .build();
    }

}
